package com.netty.imp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.apache.commons.lang3.StringUtils;
import org.msgpack.MessagePack;

import java.util.Objects;

/**
 * 自定义编码器，在发送消息前，对消息内容进行编码处理
 */
public class IMPEncoder extends MessageToByteEncoder<IMMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, IMMessage msg, ByteBuf out) throws Exception {
        out.writeBytes(new MessagePack().write(msg));
    }


    public String encode(IMMessage msg) {
        if (Objects.isNull(msg)) {
            return "";
        }
        StringBuilder builder = new StringBuilder(String.format("[%s][%s]", msg.getCmd(), msg.getTime()));
        if (IMP.LOGIN.name().equals(msg.getCmd()) || IMP.FLOWER.name().equals(msg.getCmd())) {
            builder.append(String.format("[%s][%s]", msg.getSender(), msg.getTerminal()));
        } else if (IMP.CHAT.name().equals(msg.getCmd())) {
            builder.append(String.format("[%s]", msg.getSender()));
        } else if (IMP.SYSTEM.name().equals(msg.getCmd())) {
            builder.append(String.format("[%s]", msg.getOnline()));
        }
        if (StringUtils.isNotBlank(msg.getContent())) {
            builder.append(String.format(" - %s", msg.getContent()));
        }
        return builder.toString();
    }
}
